﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lg.Core.Extensions;

namespace Lg.Core.Form.Types
{
    public class Radio : BaseType, IType
    {
        /// <summary>
        /// 前端以字符串数组的方式提交
        /// </summary>
        public List<Option>? Options { get; set; }
        /// <summary>
        /// 横向/竖向，取值 "inline"/"block"
        /// </summary>
        public string? Display { get; set; }
        public bool OtherValueRequired { get; set; }
        /// <summary>
        /// 其它附加值
        /// </summary>
        public string? OtherValue { get; set; }
        /// <summary>
        /// 使用图标选项
        /// </summary>
        public bool IconOptions { get; set; }
        public void Verify()
        {
            if (this.IsRender)
            {
                if (Required)
                {
                    Validate.Required(this.Value, $"{this.Title},为必选项,不可为空！");
                }
            }
        }
        public override FormData? SetValue(JObject formData)
        {
            string? value = formData[this.Name!]?.ToString() ?? "";
            if (!string.IsNullOrEmpty(value))
            {
                if (value == "lg-no-render")
                {
                    this.IsRender = false;
                    value = "";
                }
                else
                {
                    OptionValue? option = value.ToModel<OptionValue>();
                    if (option != null)
                    {
                        value = option.value;
                    }
                }
            }
            this.Value = value;
            return this.GetValue();
        }

        public void GetSaveDbValue(Dictionary<string, dynamic> formData, string inputValue)
        {
            if (string.IsNullOrEmpty(inputValue))
            {
                formData.Add(Name, "");
                return;
            }
            else
            {
                var op = Options?.FirstOrDefault(o => o.Text == inputValue);
                if (op != null)
                {
                    formData.Add(Name, new { opid = op.Id, value = inputValue });
                    return;
                }
                else
                {
                    formData.Add(Name, new { opid = 0, value = inputValue });
                    return;
                }
            }

        }
    }
}
